-- cmd_one_click_buy
-- Create by huanghr
-- 一键购买材料

local canBuyMaterial;
local buyMaterial;
local calcChange;
local fixCost;
local tryCost;

-- 能否购买原材料
function canBuyMaterial(needMaterial)
    local cost = FormulaM.invoke("CALC_BUY_MATERIAL_COST", needMaterial);
    cost = fixCost(cost);

    -- 判断消耗是否足够
    return BonusM.isUserCostEnough(cost);
end

-- 购买原材料
function buyMaterial(classId)
    local needMaterial = CompoundM.getNeedMaterial(classId);

    local ret = {};
    for classId, needNum in pairs(needMaterial) do
        table.insert(ret, {classId = classId, needNum = needNum});
    end
    needMaterial = ret;

    -- 计算能否购买
    if not canBuyMaterial(needMaterial) then
        return false;
    end

    -- 扣除属性
    local cost = FormulaM.invoke("CALC_BUY_MATERIAL_COST", needMaterial);

    -- 找零
    local change = calcChange(cost);

    -- 修正扣除
    cost = fixCost(cost);

    if not tryCost(cost) then
        -- 扣除失败了
        return false;
    end

    local bonusList = {};
    for k, v in pairs(needMaterial) do
        -- SLIMEC-4416，剔除掉古遗迹碎片
        if ITEM_ID_RELIC ~= v.classId then
            local bonus = {1, v.classId, v.needNum};
            table.insert(bonusList, bonus);
        end
    end

    -- 奖励
    for _, bonus in pairs(bonusList) do
        BonusM.doBonus(bonus, "cmd_one_click_buy");
    end

    -- 找零
    local bonusList, isFire = CompoundM.changeBonus(change);

    -- 抛出事件
    EventMgr.fire(event.ONE_CLICK_BUY);

    if isFire then
        -- 找零
        EventMgr.fire(event.GET_BUY_MATERIAL_CHANGE, {["bonusList"] = bonusList,})
    end

    -- 同步
    local v = {
        ["class_id"] = classId,
    };
    SyncM.addMessage("CMD_ONE_CLICK_BUY", v);
    SyncM.startSync();

    return true;
end

-- 尝试扣除
function tryCost(cost, costDesc)
    local ok = true;
    for _, arr in pairs(cost) do
        if arr[1] == 1 then
            if not ItemM.costAmount(ME.user, arr[2], arr[3]) then
                ok = false;
                break;
            end
        elseif arr[1] == 2 then
            if not ME.user:costAttrib(arr[2], arr[3]) then
                ok = false;
                break;
            end
        end
    end

    return ok;
end

-- 计算找零
function calcChange(cost)
    local change = 0;
    for _, perCost in ipairs(cost) do
        if perCost[1] == 2 and perCost[2] == "gem" then
            -- 钻石类的要计算找零
            local gemCost = math.ceil(perCost[3] / 1000);
            change = gemCost * 1000 - perCost[3];
            break;
        end
    end
    return change;
end

-- 修正扣除
function fixCost(cost)
    for _, perCost in ipairs(cost) do
        if perCost[1] == 2 and perCost[2] == "gem" then
            -- 钻石类的要除以1000
            perCost[3] = math.ceil(perCost[3] / 1000);
        end
    end

    return cost;
end

function Operation.cmd_one_click_buy(classId)
    -- 购买
    return buyMaterial(classId);
end
